package com.framework.loippi.controller.api.callback;

import com.framework.loippi.controller.api.ApiBaseController;
import com.framework.loippi.controller.api.SubscribeController;
import com.framework.loippi.entity.*;
import com.framework.loippi.service.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller("payCallBackAPIController")
@RequestMapping("/api/payCallBack")
public class PayCallBackAPIController extends ApiBaseController {

    private final static Logger logger = LoggerFactory.getLogger(PayCallBackAPIController.class);

    @Resource
    private NoticeService noticeService;
    @Resource
    private NoticeToUserService noticeToUserService;
    @Resource
    private TOrderService orderService;
    @Resource
    private TMedicineService tMedicineService;
    @Resource
    private OrderItemService orderItemService;
    @Resource
    private SubscribeService subscribeService;
    @Resource
    private PatientService patientService;

    @Resource
    TPreferentialService preferentialService;

    @RequestMapping(value = "/orderpay/{payType}/{orderId}.json")
    public void updateOrder(HttpServletResponse response, @PathVariable(value = "payType") Integer payType, @PathVariable(value = "orderId") String orderId) {
//        System.out.println("this is orderId:" + orderId);
//        System.out.println("this is isOPenGroup:" + isOpenGroup);
        logger.debug("【测试支付回调】/orderpay/" + payType + "/" + orderId + ".json");
//      todo 更新订单状态
        TOrder order = orderService.find(Long.valueOf(orderId));
        if (order == null ) {
            new RuntimeException("订单不存在");
        }
        // 查询订单包含的用户ID以及推荐人ID，记录推荐人的优惠数据

//      支付成功在减去商品数量,端口库存也相应减去
        List<OrderItem> orderItemList = orderItemService.findByOrderId(Long.valueOf(orderId));
        for (OrderItem ot : orderItemList) {
            TMedicine medicine = tMedicineService.find(ot.getMedicineId());
            medicine.setSellcount(medicine.getSellcount() == null ? 0 : medicine.getSellcount() + ot.getMedicineCount());
            medicine.setRepertory(medicine.getRepertory() - ot.getMedicineCount());
            tMedicineService.update(medicine);
        }

//      生成订单通知
        Notice notice = new Notice();
        NoticeToUser noticeToUser = new NoticeToUser();
        order.setOrderStatus(1);
        order.setPayType(payType);
        order.setPayTime(new Date());
        orderService.update(order);
        notice.setContent("您支付了一个订单");
        notice.setCreateTime(new Date());
        notice.setType(1);
        Long save = noticeService.save(notice);
        if (save > 0) {
            noticeToUser.setUserId(order.getUserId());
            noticeToUser.setNoticeId(notice.getId());
            noticeToUser.setNoticeStatus(0);
            noticeToUser.setCreateTime(new Date());
            noticeToUserService.save(noticeToUser);
        }
        paySuccess(payType, response);
        if(order.getRecommendId()!=null){
            //订单是分享购买的并且只有一个货物对应
            List<OrderItem> itemList = orderItemService.findByOrderId(order.getId());
            for (OrderItem item: itemList){
                preferentialService.updateByUidAndGid(order.getRecommendId(),item.getMedicineId());
            }
        }

    }

    @RequestMapping(value = "/subscribePay/{payType}/{subscribeId}.json")
    public void updateSubscribe(HttpServletResponse response, @PathVariable(value = "payType") Integer payType, @PathVariable(value = "subscribeId") String subscribeId) {
//        System.out.println("this is orderId:" + orderId);
//        System.out.println("this is isOPenGroup:" + isOpenGroup);

        logger.debug("【测试支付回调】/subscribePay/" + payType + "/" + subscribeId + ".json");

//      todo 更新订单状态
        Subscribe subscribe = subscribeService.find(Long.valueOf(subscribeId));
        if (subscribe == null ) {
            new RuntimeException("预约不存在");
        }
        subscribe.setPayStatus(1); //0.待支付，1已支付
        subscribe.setStatus(1); // 0取消,1待就诊,2进行中,3已完成
        Long nowNum = subscribeService.findSubNumByDate(subscribe.getSubscribeTime());
        synchronized (SubscribeController.class) {
            if (nowNum == null || nowNum == 0) {
                nowNum = 1L;
            } else {
                nowNum++;
            }
        }
        subscribe.setSubscribeNu(nowNum);
        subscribe.setPayTime(new Date());
        Long result = subscribeService.update(subscribe);

//      生成预约通知
        Notice notice = new Notice();
        NoticeToUser noticeToUser = new NoticeToUser();
        notice.setContent("您" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(subscribe.getSubscribeTime()) + "有一个预约");
        notice.setCreateTime(new Date());
        notice.setType(0);
        Long save = noticeService.save(notice);
        if (save > 0) {
            noticeToUser.setUserId(patientService.find(subscribe.getPatientId()).getUserId());
            noticeToUser.setNoticeId(notice.getId());
            noticeToUser.setNoticeStatus(0);
            noticeToUser.setCreateTime(new Date());
            noticeToUserService.save(noticeToUser);
        }
        paySuccess(payType, response);

    }

    public void paySuccess(
            Integer payType,
            HttpServletResponse response) {
        String result = "success";
        if (payType == 2) {
            result = "success";
        } else if (payType == 1) {
            result = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        }
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(result);
        } catch (Exception e) {
            out.println("FAIL");
            e.printStackTrace();
        } finally {
            out.close();
        }
    }


//  订单号
    public static String generateBn(Long userId) {
        return new SimpleDateFormat("yyMMddHHmmss").format(new Date()) + userId;
    }
}
